package com.wuliu.web.delayqueue;

import com.wuliu.common.enums.RedisDelayQueueEnum;
import com.wuliu.common.utils.RedissonUtils;
import com.wuliu.common.utils.spring.SpringUtils;
import com.wuliu.system.service.delayqueue.RedisDelayQueueHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 启动延迟队列
 *
 * @author realue
 * @version 1.0
 * @date 2023-11-17 10:20
 */
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {

    @Resource
    private RedissonUtils redissonUtils;
    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void run(String... args) throws Exception {
        RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
        for (RedisDelayQueueEnum queueEnum : queueEnums) {
            new Thread(() -> {
                try {
                    while (true) {
                        Object value = redissonUtils.getDelayQueue(queueEnum.getQueueName());
                        RedisDelayQueueHandle redisDelayQueueHandle = SpringUtils.getBean(queueEnum.getBeanId());
                        taskExecutor.submit(() -> redisDelayQueueHandle.execute(value));
                    }
                } catch (InterruptedException e) {
                    log.error("Redis延迟队列异常中断:{}", e.getMessage());
                }
            }).start();
        }
        log.info("Redis延迟队列启动成功...");
    }
}
